package com.ultrapower.util;

import com.ultrapower.buffer.AutomaticBuffer;
import com.ultrapower.buffer.Buffer;

public class ApplicationMapStatisticsUtils {

	public static byte[] makeRowKey(String applicationName, short applicationType, long timestamp) {
		if (applicationName == null) {
			throw new NullPointerException("applicationName must not be null");
		}
		final byte[] applicationNameBytes = BytesUtils.toBytes(applicationName);

		final Buffer buffer = new AutomaticBuffer(2 + applicationNameBytes.length + 2 + 8);
		// buffer.put2PrefixedString(applicationName);
		buffer.putShort((short) applicationNameBytes.length);
		buffer.putBytes(applicationNameBytes);
		buffer.putShort(applicationType);
		long reverseTimeMillis = CommonUtils.reverseTimeMillis(timestamp);
		buffer.putLong(reverseTimeMillis);
		return buffer.getBuffer();
	}

	public static String getDestApplicationNameFromColumnName(byte[] bytes) {
		final short length = BytesUtils.bytesToShort(bytes, 4);
		return BytesUtils.toStringAndRightTrim(bytes, 6, length);
	}

	public static short getDestServiceTypeFromColumnName(byte[] bytes) {
		return BytesUtils.bytesToShort(bytes, 0);
	}

	public static String getDestApplicationNameFromColumnNameForUser(byte[] bytes, short destServiceType) {
		String destApplicationName = getDestApplicationNameFromColumnName(bytes);
		String destServiceTypeName = destServiceType + "";// destServiceType.getName();
		return destApplicationName + "_" + destServiceTypeName;
	}

	public static short getHistogramSlotFromColumnName(byte[] bytes) {
		return BytesUtils.bytesToShort(bytes, 2);
	}

	public static String getHost(byte[] bytes) {
		int offset = 6 + BytesUtils.bytesToShort(bytes, 4);

		if (offset == bytes.length) {
			return null;
		}
		return BytesUtils.toStringAndRightTrim(bytes, offset, bytes.length - offset);
	}
}
